/**
 * Copyright (c) 2015-2020, wss 王山山
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wss.utils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import com.wss.utils.exception.BeanException;

/**
 * JavaBean工具类
 * 
 * @author wss
 *
 */
public final class BeanUtil {
	private BeanUtil() {}
	
	/**
	 * 获取对象指定属性名的属性值
	 * 
	 * @param obj			对象
	 * @param property		属性名
	 * @return				属性值
	 */
	public static Object get(Object obj, String property) {
		try {
			PropertyDescriptor propertyDesc = new PropertyDescriptor(property, obj.getClass());
			Method readMethod = propertyDesc.getReadMethod();
			return readMethod.invoke(obj);
		} catch (IntrospectionException | ReflectiveOperationException e) {
			throw new BeanException(e);
		}
	}
	
	/**
	 * 设置对象指定属性的属性值
	 * 
	 * @param obj			对象
	 * @param property		属性名
	 * @param value			属性值
	 */
	public static void set(Object obj, String property, Object value) {
		try {
			PropertyDescriptor propertyDesc = new PropertyDescriptor(property, obj.getClass());
			Method writeMethod = propertyDesc.getWriteMethod();
			writeMethod.invoke(obj, value);
		} catch (IntrospectionException | ReflectiveOperationException e) {
			throw new BeanException(e);
		}
	}
}
